package gatperdut.chato.core.interpreter.actions;

import gatperdut.chato.constants.CSConstantsCommandResult.CommandExecutionResult;
import gatperdut.chato.core.characters.BaseController;
import gatperdut.chato.core.interpreter.actions.generic.Action;
import gatperdut.chato.core.interpreter.grammar.comminfo.EmptyInfo;
import gatperdut.chato.core.item.ItemController;
import gatperdut.chato.core.item.inventory.BoxInventoryController;

public class EmptyAction extends Action {

    public EmptyAction( EmptyInfo info, BaseController entityController ) {
        super( info, entityController );
    }

    @Override
    public CommandExecutionResult perform() {
        checkForRunningCraft();

        if ( emptyEmote() ) {
            getEntityController().tx( "Empty emotes are not allowed." );
            return CommandExecutionResult.OK;
        }

        String emote = getLastPartEmote();
        if ( emote == null ) {
            getEntityController().tx( "Check your emote." );
            return CommandExecutionResult.OK;
        }

        if ( !checkUnindexedWord( getInfo().getEmptyFrom() ) ) {
            return CommandExecutionResult.OK;
        }

        synchronized ( getEntityController().getInventoryController() ) {
            ItemController emptyFrom = getEntityController().getInventoryController().getHeldItemController( getInfo().getEmptyFrom() );
            if ( emptyFrom == null ) {
                getEntityController().tx( "You don't seem to be holding that." );
                return CommandExecutionResult.OK;
            }
            if ( emptyFrom.getInventoryController() == null ) {
                getEntityController().tx( emptyFrom.getShortDesc() + " is not a container." );
                return CommandExecutionResult.OK;
            }
            if ( emptyFrom.getInventoryController().isEmpty() ) {
                getEntityController().tx( emptyFrom.getShortDesc() + " is empty." );
                return CommandExecutionResult.OK;
            }

            synchronized ( emptyFrom.getInventoryController() ) {
                BoxInventoryController bic = emptyFrom.getInventoryController();
                synchronized ( getEntityController().getRoomController().getInventoryController() ) {
                    bic.dumpInto( getEntityController().getRoomController().getInventoryController() );
                }
                getEntityController().getEchoes().txEmptyOnGround( emptyFrom, emote );
            }
        }
        return CommandExecutionResult.OK;
    }

    @Override
    public EmptyInfo getInfo() {
        return (EmptyInfo) super.getInfo();
    }

    @Override
    public boolean interruptsCrafting() {
        return false;
    }
}
